const Book = require('../models/book');
const BookInstance = require('../models/bookinstance');
const Author = require('../models/author');
const Genre = require('../models/genre');
const async = require('async');
const {body,validationResult} = require('express-validator/check');
const {sanitizeBody} = require('express-validator/filter');

exports.index = (req,res)=>{
    //console.log('time of start: '+new Date().getTime());
    async.parallel({
        book_count:function (cb) {
            Book.countDocuments({},cb);
        },
        book_instance_count:function (cb) {
            BookInstance.countDocuments({},cb);
        },
        book_instance_available:function(cb){
            BookInstance.countDocuments({status:'可供借阅'},cb);
        },
        author_count:function (cb) {
            Author.countDocuments({},cb)
        },
        genre_count:function (cb) {
            Genre.countDocuments({},cb)
        }
    },function (err, results) {
        //console.log('time of end: '+new Date().getTime());
        res.render('index',{title:'Local Library Home',error:err,data:results})
    })
};


exports.book_list = (req,res,next)=>{
    Book.find({},'title author')
        .populate('author')
        .exec(function (err, list_books) {
            if(err){return next(err)}
            res.render('book_list',{title:'Book List',book_list:list_books})
        });
};

exports.book_detail = (req,res,next)=>{
    async.parallel({
        book:function (cb) {
            Book.findById(req.params.id)
                .populate('author')
                .populate('genre')
                .exec(cb);
        },
        book_instances:function (cb) {
            BookInstance.find({book:req.params.id}).exec(cb);
        }
    },function (err, results) {
        if(err||results.book==null){
            if(results.book==null){
                err = new Error('Book not found');
                err.statusCode = 404;
            }
            next(err);
        }else{
            res.render('book_detail',{
                title:'当前书籍：'+results.book.title,
                book:results.book,
                book_instances:results.book_instances
            })
        }
    });
};

exports.book_create_get = (req,res,next)=>{
    async.parallel({
        authors:function (cb) {
            Author.find(cb);
        },
        genres:function (cb) {
            Genre.find(cb);
        }
    },function (err, results) {
        if(err) return next(err);
        res.render('book_form',{title:'创建书籍',authors:results.authors,genres:results.genres})
    });
};
exports.book_create_post = [
    (req,res,next)=>{
        let genre = req.body.genre||[];
        //console.log({genre});
        if(!genre instanceof Array){
            req.body.genre = new Array(genre);
        }
        next();
    },
    body('title','title is required').isLength({min:1}).trim(),
    body('author','author is required').isLength({min:1}).trim(),
    body('summary','summary is required').isLength({min:1}).trim(),
    body('isbn','isbn is required').isLength({min:1}).trim(),
    sanitizeBody('*').escape(),
    (req,res,next)=>{
        const errors = validationResult(req);
        let book = new Book({
            ...req.body
        });
        if(!errors.isEmpty()){
            //validate failed
            async.parallel({
                authors:function (cb) {
                    Author.find(cb);
                },
                genres:function (cb) {
                    Genre.find(cb);
                }
            },function (err, results) {
                if(err) return next(err);
                for(let i=0;i<results.genres.length;i++){
                    if(book.genre.indexOf(results.genres[i]._id)>-1){
                        results.genres[i].checked='true';
                    }
                }
                res.render('book_form',{title:'重新创建书籍',authors:results.authors,genres:results.genres,book,errors:errors.array()})
            });
        }else{
            book.save(function (err) {
                if(err) return next(err);
                res.redirect(book.url);
            })
        }
    },
];

exports.book_update_get = (req,res,next)=>{
    async.parallel({
        book:function (cb) {
            Book.findById(req.params.id).exec(cb);
        },
        authors:function (cb) {
            Author.find(cb);
        },
        genres:function (cb) {
            Genre.find(cb)
        }
    },function (err, results) {
        if(err) return next(err);
        if(results.book==null){
            res.redirect('/catalog/books');
        }
        for(let i=0;i<results.genres.length;i++){
            if(results.book.genre.indexOf(results.genres[i]._id)>-1){
                results.genres[i].checked='true';
            }
        }
        res.render('book_update',{title:'编辑书籍',book:results.book,authors:results.authors,genres:results.genres})
    });
};
exports.book_update_post = [
    (req,res,next)=>{
        let genre = req.body.genre||[];
        //console.log({genre});
        if(!genre instanceof Array){
            req.body.genre = new Array(genre);
        }
        next();
    },
    body('title','title is required').isLength({min:1}).trim(),
    body('author','author is required').isLength({min:1}).trim(),
    body('summary','summary is required').isLength({min:1}).trim(),
    body('isbn','isbn is required').isLength({min:1}).trim(),
    sanitizeBody('*').escape(),
    (req,res,next)=>{
        const errors = validationResult(req);
        let book = new Book({
            ...req.body,
            _id:req.params.id
        });
        if(!errors.isEmpty()){
            //validate failed
            async.parallel({
                authors:function (cb) {
                    Author.find(cb);
                },
                genres:function (cb) {
                    Genre.find(cb);
                }
            },function (err, results) {
                if(err) return next(err);
                for(let i=0;i<results.genres.length;i++){
                    if(book.genre.indexOf(results.genres[i]._id)>-1){
                        results.genres[i].checked='true';
                    }
                }
                res.render('book_update',{title:'重新更新书籍',authors:results.authors,genres:results.genres,book,errors:errors.array()})
            });
        }else{
            Book.findByIdAndUpdate(req.params.id,book,{},function (err,theBook) {
                if(err) return next(err);
                res.redirect(theBook.url);
            })
        }
    },
];

exports.book_delete_get = (req,res,next)=>{
    async.parallel({
        book:function (cb) {
            Book.findById(req.params.id).populate('author').populate('genre').exec(cb);
        },
        book_instances:function (cb) {
            BookInstance.find({book:req.params.id}).exec(cb);
        }
    },function (err, results) {
        if(err) return next(err);
        res.render('book_delete',{title:'删除当前书目',book:results.book,book_instances:results.book_instances})
    });
};
exports.book_delete_post = (req,res,next)=>{
    async.parallel({
        book:function (cb) {
            Book.findById(req.params.id).exec(cb);
        },
        book_instances:function (cb) {
            BookInstance.find({book:req.params.id}).exec(cb);
        }
    },function (err, results) {
        if(err) return next(err);
        if(results.book_instances&&results.book_instances.length>0){
            res.render('book_delete',{title:'删除当前书目',book:results.book,book_instances:results.book_instances});
        }else{
            Book.findByIdAndRemove(req.params.id,function (err) {
                if(err) return next(err);
                res.redirect('/catalog/books');
            })
        }

    });
};

